import Router from 'koa-router'
import Redis from 'koa-redis'
import nodeMailer from 'nodemailer'
import User from '../dbs/models/user'
import Menus from "../dbs/models/menus";
import Passport from './utils/passport'
import Email from '../dbs/congif'
import axios from './utils/axios'

let route = new Router({
  prefix: '/users'
})
let Store = new Redis().client

route.post('/signup', async (ctx, next) => {
  const {username,password,email,code} = ctx.request.body
  if (code) {
    const saveCode = await Store.hget(`nodemail:${username}`,'code')
    const saveExpire = await Store.hget(`nodemail:${username}`, 'expire')
    if (code === saveCode) {
      if (new Date().getTime() - saveExpire > 0) {
        ctx.body= {
          code: -1,
          msg: '验证码过期,请重新发送'
        }
        return false
      }
    } else {
      ctx.body= {
        code: -1,
        msg: '请填写正确的验证码'
      }
      return false
    }
  } else {
    ctx.body= {
      code: -1,
      msg: '请填写验证码'
    }
  }
  let user = await User.find({
    username
  })
  if (user.length) {
    ctx.body= {
      code: -1,
      msg: '昵称已存在'
    }
  }
  let nuser = await User.create({
    username,
    password,
    email
  })
  if (nuser) {
    let res = await axios.post('/users/signin', {
      username,password
    })
    if (res.data && res.data.code === 0) {
      ctx.body={
        code: 0,
        msg: '注册成功',
        user: res.data.user
      }
    } else {
      ctx.body={
        code: -1,
        msg: 'error'
      }
    }
  } else {
    ctx.body={
      code: -1,
      msg: '注册失败'
    }
  }

})

route.post('/signin', async (ctx,next) => {
  return Passport.authenticate('local',function (err,user,info,status) {
        if (err) {
          ctx.body={
            code:-1,
            msg: err
          }
        }else {
          if (user) {
            ctx.body={
              code:0,
              msg: '登录成功',
              user
            }
            return ctx.login(user)
          }else {
            ctx.body={
              code:1,
              msg:info
            }
          }
        }
  })(ctx,next)
})

route.post('/verify', async (ctx, next) => {
  let username = ctx.request.body.username
  console.log('verify')
  const saveExpire = await Store.hget(`nodemail:${username}`, 'expire')
  if (saveExpire&& new Date().getTime() - saveExpire < 0) {
    ctx.body = {
      code: -1,
      msg: '验证请求频繁'
    }
    return false
  }
  let transport = nodeMailer.createTransport({
    host: Email.smtp.host,
    port: 587,
    // true就监听465端口 否的话就是其他端口
    secure: false,
    auth: {
      user: Email.smtp.user,
      pass: Email.smtp.pass
    }
  })
    let  ko = {
      code: Email.smtp.code(),
      expire: Email.smtp.expire(),
      email: ctx.request.body.email,
      user: ctx.request.body.username
    }
    let mailOption = {
      from: `"认证邮件"<${Email.smtp.user}>`,
      to: ko.email,
      subject: '<高仿美团注册码>',
      html: `您的验证码是${ko.code}`
    }

    await transport.sendMail(mailOption, async (error,info) => {
      if (error) {
        return console.log(error)
      }else {
        await Store.hmset(`nodemail:${ko.user}`,'code',ko.code,'expire',ko.expire,'email',ko.email)
        console.log('已经发出')
        ctx.body={
          code:0,
          msg:'验证码已发送，有效期60秒'
        }
      }
    })
})

route.get('/exit',async (ctx,next)=>{
  await ctx.logout()
  if (!ctx.isAuthenticated()) {
    ctx.body={
      code: 0
    }
  }else {
    ctx.body={
      code: -1
    }
  }
})
route.get('/getUser',async (ctx) => {
  if (ctx.isAuthenticated()) {
    const {username,email} = ctx.session.passport.user
    ctx.body = {
      code: 0,
      user: username,
      email
    }
  } else {
    ctx.body = {
      code: 0,
      user: '',
      email: ''
    }
  }
})

export default route
